package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import com.itheima.reggie.service.ShoppingCartService;
import com.itheima.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders){
        log.info("订单数据:{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");

    }
/**
 * 订单信息分页查询
 * @param page 当前查询页码
 * @param pageSize 每页展示记录数
 * @param number 订单号- 可选参数
 * @return
 */
@GetMapping("/page")
    public R page(int page,int pageSize,String number,String beginTime,String endTime){
    log.info("page={},pageSize={},name={}",page,pageSize,number);

//    构造分页构造器
    Page pageInfo = new Page<>(page, pageSize);

//    构造条件构造器
    LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.like(StringUtils.isNotEmpty(number),Orders::getNumber,number);
    queryWrapper.ge(beginTime!=null,Orders::getCheckoutTime,beginTime);
    queryWrapper.le(endTime!=null,Orders::getCheckoutTime,endTime);
//    添加排序条件
    queryWrapper.orderByDesc(Orders::getCheckoutTime);

//    执行查询
    orderService.page(pageInfo,queryWrapper);
    List<Orders> records = pageInfo.getRecords();
    records.stream().map((item)->{
        item.setUserName("用户"+item.getUserId());
        return item;
    }).collect(Collectors.toList());
    return R.success(pageInfo);


}

//订单状态修改
    @PutMapping
    public R updateStatus(@RequestBody Orders orders){
//    构造条件构造器
        LambdaUpdateWrapper<Orders> updateWrapper = new LambdaUpdateWrapper<>();
       updateWrapper.eq(Orders::getId,orders.getId());
       updateWrapper.set(Orders::getStatus,orders.getStatus());
       orderService.update(updateWrapper);
    return R.success("修改订单状态成功");
    }

    @Autowired
    private OrderDetailService orderDetailService;
   @Autowired
    private UserService userService;
        /**
         * 用户端展示自己的订单分页查询
         * @param page
         * @param pageSize
         * @return
         */
        @GetMapping("/userPage")
        public R<Page> page(int page, int pageSize){
           Page<OrdersDto> dtoPage= orderService.userPage(page,pageSize);
           return R.success(dtoPage);
        }

    /**
     * 用户端再来一单
     * 点击再来一单，跳转购物车页面，判断购物车是否有东西，
     * 有东西就清空购物车数据，再显示订单明细数据。
     * 没数据，就直接回显数据
     * @return
     */
    @Autowired
    private ShoppingCartService shoppingCartService;
    @PostMapping("/again")
//    public R again(@RequestBody Map<String,String> map){
    public R again(@RequestBody Orders orders){
//        String ids = map.get("id");
//        long id = Long.parseLong(ids);
//       获取订单id，根据订单id获取到该单的具体明细,将明细保存到购物车中，进行数据的回显
        Long id = orders.getId();
        LambdaQueryWrapper<OrderDetail> queryWrapper= new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderDetail::getOrderId,id);
//        获取订单明细表
        List<OrderDetail> list = orderDetailService.list(queryWrapper);
//        清空购物车
        shoppingCartService.clean();
//        获取当前用户登录的id
        Long userId = BaseContext.getCurrentId();

        List<ShoppingCart> shoppingCarts=list.stream().map((item)->{
            ShoppingCart shoppingCart = new ShoppingCart();
            shoppingCart.setUserId(userId);
            shoppingCart.setName(item.getName());
            shoppingCart.setImage(item.getImage());
            Long dishId = item.getDishId();
            Long setmealId=item.getSetmealId();
            if(dishId!=null){
//                添加到购物车的是菜品
             shoppingCart.setDishId(dishId);
            }else{
//                添加到购物车的是套餐
                shoppingCart.setSetmealId(setmealId);
            }
            shoppingCart.setDishFlavor(item.getDishFlavor());
            shoppingCart.setNumber(item.getNumber());
            shoppingCart.setAmount(item.getAmount());
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());
        shoppingCartService.saveBatch(shoppingCarts);
        return R.success("再来一单");
    }


}